using System;
using System.Collections;
using SecuBat.Common;
using SecuBat.Work;

namespace SecuBat.Threading
{
	/// <summary>
	/// Summary description for ThreadControllerCollection.
	/// </summary>
	public class ThreadControllerCollection : SharedData, IDisposable
	{
		Hashtable _threadControllers;
		int _maxThreads;

		public ThreadControllerCollection(int maxThreads)
		{
			_threadControllers = new Hashtable();
			_maxThreads = maxThreads;
		}

		public ThreadController AddController(Task task)
		{
			WriteLock();
			ThreadController tc = null;
			if (_threadControllers.Count < _maxThreads)
			{
				WorkerThread thread = new WorkerThread(task);
				tc = new ThreadController(thread);
				_threadControllers.Add(thread.GetHashCode(), tc);
			}
			WriteRelease();
			return tc;
		}

		public bool RemoveController(int threadHashCode)
		{
			WriteLock();
			bool contained = _threadControllers.Contains(threadHashCode);
			if (contained)	
				_threadControllers.Remove(threadHashCode);
			WriteRelease();
			return contained;
		}

		public int Count
		{
			get
			{
				ReadLock();
				int i = _threadControllers.Count;
				ReadRelease();
				return i;
			}
		}
		
		#region IDisposable Members

		public void Dispose()
		{
			WriteLock();
			foreach (Object key in this._threadControllers)
			{
				ThreadController c = this._threadControllers[key] as ThreadController;
				if (c != null)
				{
					c.Terminate(10);
					_threadControllers.Remove(key);
					c = null;
				}
			}
			WriteRelease();
		}

		#endregion
	}
}
